//
//  SessionViewController.m
//  ivcs_ios_demo
//
//  Created by zealcomm user on 2020/10/24.
//  Copyright © 2020 zealcomm user. All rights reserved.
//

#import "SessionViewController.h"
#import "MessageViewController.h"
#import "FormTableViewController.h"
#import "WebLoginViewController.h"
#import "HandSignViewController.h"
@interface SessionViewController ()<IVCSSDKDelegate,CCSClientDelegate,HandSignViewControllerDelegate>

@property (weak, nonatomic) IBOutlet RTCEAGLVideoView *localVideoView;
@property (weak, nonatomic) IBOutlet RTCEAGLVideoView *firstAgent;
@property (weak, nonatomic) IBOutlet RTCEAGLVideoView *secondAgent;
@property (weak, nonatomic) IBOutlet RTCEAGLVideoView *screenVideo;
@property(assign,nonatomic)BOOL isHoldOn;//是否正在转接其他坐席，默认是否
@property(assign,nonatomic)int position;

@end

@implementation SessionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.position = 0;
    self.isHoldOn = false;
    [self start];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"离开" style:UIBarButtonItemStyleDone target:self action:@selector(leave)];
    UIBarButtonItem *switchCamera = [[UIBarButtonItem alloc] initWithTitle:@"切换摄像头" style:UIBarButtonItemStyleDone target:self action:@selector(switchCamera)];
    UIBarButtonItem *bussiness = [[UIBarButtonItem alloc] initWithTitle:@"互动消息" style:UIBarButtonItemStyleDone target:self action:@selector(goToMessage)];
    UIBarButtonItem *mute = [[UIBarButtonItem alloc] initWithTitle:@"静音" style:UIBarButtonItemStyleDone target:self action:@selector(audioMuteOperate)];
    UIBarButtonItem *unmute = [[UIBarButtonItem alloc] initWithTitle:@"恢复声音" style:UIBarButtonItemStyleDone target:self action:@selector(audiounMuteOperate)];
    self.navigationItem.rightBarButtonItems = @[left,switchCamera,bussiness,mute,unmute];
}


-(void)audiounMuteOperate{
    [self.ivcsSdk unmuteWithMediaType:IRTCTrackKindAudio onSuccess:^{
        NSLog(@"success");
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"111,error,,%@",error);
    }];
}

-(void)audioMuteOperate{
    [self.ivcsSdk muteWithMediaType:IRTCTrackKindAudio onSuccess:^{
        NSLog(@"22success");
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"111,error,,%@",error);
    }];
}

-(void)goToMessage{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
       MessageViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"messageVc"];
       vc.ivcsSdk = self.ivcsSdk;
       vc.sessionId = self.sessionId;
       [self.navigationController pushViewController:vc animated:true];
}

-(void)viewWillDisappear:(BOOL)animated{
    
}

-(void)leave{
    [self.ivcsSdk quitSession:nil onSuccess:^{
        NSLog(@"quit session success");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:false];
        });
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"222quit sessionerror,%@",error);
        [self.navigationController popViewControllerAnimated:false];
    }];
}

-(void)switchCamera{
    if (self.position == 0) {
        [self.ivcsSdk switchCameraDevicePosition:AVCaptureDevicePositionBack onSuccess:^{
        } onFailure:^(NSError * _Nonnull error) {
            NSLog(@"error,,%@",error);
        }];
        self.position = 1;
    }else{
        [self.ivcsSdk switchCameraDevicePosition:AVCaptureDevicePositionFront onSuccess:^{
        } onFailure:^(NSError * _Nonnull error) {
            NSLog(@"error,,%@",error);
        }];
        self.position = 0;
    }
   
}

-(void)start{
    self.ivcsSdk.delegate = self;
    self.ivcsSdk.ccsClient.delegate = self;
    [self.ivcsSdk startVideoWithLabel:@"customer" onSuccess:^(IRTCLocalStream * _Nonnull localStream) {
        [[AVAudioSession sharedInstance]
         overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
         error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            RTCVideoTrack *track = localStream.mediaStream.videoTracks.lastObject;
            [track addRenderer:self.localVideoView];
        });
        if (self.isRobotAgent) {
            NSDictionary *data = [self.user valueForKey:@"data"];
            [self.ivcsSdk readyToTalk:@{
                @"picture":[[data valueForKey:@"profile"] valueForKey:@"picture"],
                @"fullName":[[data valueForKey:@"profile"] valueForKey:@"fullName"],
                @"gender":[[data valueForKey:@"profile"] valueForKey:@"gender"]
            } toRoles:@"agents" onSuccess:^{
                NSLog(@"tell robot agent success");
            } onFailure:^(NSError * _Nonnull error) {
                NSLog(@"tell robot agent error,%@",error);
            }];
        }
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"start video error,,%@",error);
    }];
    
    
    
}


-(void)onStreamRemoveWithLabel:(NSString *)label andStream:(IRTCRemoteStream *)stream{
    NSLog(@"1onStreamRemoveWithLabel...%@,,%@",label,stream);
}

-(void)onStreamAddWithLabel:(NSString *)label andStream:(IRTCRemoteStream *)stream{
    NSLog(@"1onStreamAddWithLabel...%@,,%@",label,stream);
    if ([label isEqualToString:@"screen"]) {
        [self.ivcsSdk renderStreamWithLabel:label remoteStream:stream renderView:self.screenVideo onSuccess:^{
            NSLog(@"render success!!,,%@,%lu",label,(unsigned long)label.length);
        } onFailure:^(NSError * _Nonnull error) {
            NSLog(@"render failed%@",error);
        }];
    }else{
        if ([label isEqualToString:@"customer"]) {
            if (self.isRobotAgent) {
                [self.ivcsSdk renderStreamWithLabel:label remoteStream:stream renderView:self.firstAgent onSuccess:^{
                    NSLog(@"render success!!,,%@,%lu",label,(unsigned long)label.length);
                } onFailure:^(NSError * _Nonnull error) {
                    NSLog(@"render failed%@",error);
                }];
            }
        }else{
            if (label == nil && [label isKindOfClass:[NSNull class]] && [label length] == 0) {
                NSLog(@"is null stream");
                return;
            }else if ([self.ivcsSdk.ccsClient.userList count]>1) {
                [self.ivcsSdk renderStreamWithLabel:label remoteStream:stream renderView:self.secondAgent onSuccess:^{
                    NSLog(@"render success!!,,%@,%lu",label,(unsigned long)label.length);
                } onFailure:^(NSError * _Nonnull error) {
                    NSLog(@"render failed%@",error);
                }];
            }else{
                [self.ivcsSdk renderStreamWithLabel:label remoteStream:stream renderView:self.firstAgent onSuccess:^{
                    NSLog(@"render success!!,,%@,%lu",label,(unsigned long)label.length);
                } onFailure:^(NSError * _Nonnull error) {
                    NSLog(@"render failed%@",error);
                }];
            }
        }
    }
}

#pragma mark ccsclientDelegate
-(void)ccsErrorWithCode:(IVCSSDKErrorCode)code andMessage:(NSString *_Nullable)message{
    NSLog(@"44,,%ld,%@",(long)code,message);
}

-(void)onDrop:(NSDictionary *_Nonnull)message{
    NSLog(@"333onDrop,%@",message);
}

-(void)onJoinSession:(NSDictionary *_Nonnull)personInfo{
    NSLog(@"22onJoinSession,%@",personInfo);
    self.isHoldOn = false;//有新坐席加入，修改转接状态为false
}

-(void)onQuitSession:(NSDictionary *_Nonnull)personInfo{
    NSLog(@"11quit session,%@",personInfo);
    //判断是否是机器人坐席
    if ([personInfo valueForKey:@"user"]) {
        if ([[personInfo valueForKey:@"user"] valueForKey:@"profile"]) {
                  if ([[[[personInfo valueForKey:@"user"] valueForKey:@"profile"] valueForKey:@"isRobot"] isEqualToNumber:[NSNumber numberWithInt:1]]) {
                          NSLog(@"is robot agent");
                          [self showAlert:@"机器人坐席已离开，是否离开？" onOK:^{
                              [self leave];
                          } onCancel:^{
                              
                          }];
                  }
        }else{
            if ([self.ivcsSdk.ccsClient.userList count] == 0 && self.isHoldOn) {
                [self showAlert:@"坐席已离开，正在转接其他坐席中，是否离开？" onOK:^{
                    [self leave];
                } onCancel:^{
                    
                }];
            }else{
                [self showAlert:@"坐席已离开，是否离开？" onOK:^{
                    [self leave];
                } onCancel:^{
                    
                }];
            }
        }
    }else{
        if ([self.ivcsSdk.ccsClient.userList count] == 0 && self.isHoldOn) {
            [self showAlert:@"坐席已离开，正在转接其他坐席中，是否离开？" onOK:^{
                [self leave];
            } onCancel:^{
                
            }];
        }else{
            [self showAlert:@"坐席已离开，是否离开？" onOK:^{
                [self leave];
            } onCancel:^{
                
            }];
        }
    }
}

- (void)showAlert:(NSString *)message onOK:(void(^)(void))ok onCancel:(void(^)(void))cancel{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
        ok();
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
        cancel();
                                                          }];
    [alert addAction:cancelAction];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

/// 正在转接其他坐席
-(void)onHoldOn{
    NSLog(@"onhold on");
    self.isHoldOn = true;
    [self showAlert:@"正在转接人工坐席" onOK:^{
      
    } onCancel:^{
        
    }];
}

-(void)onPhotoGuideBox{
    NSLog(@"111onPhotoGuideBox");
}

-(void)onHandSignatureRequest{
    NSLog(@"xxonHandSignatureRequest");
    [self formOperate:@"邀请手写签名" andType:3 andData:nil];
}

-(void)onFormData:(id)data{
    NSLog(@"...onform data,%@",data);
    if ([data valueForKey:@"collect"]) {
        //确认个人信息
        NSString *message = [NSString stringWithFormat:@"个人信息:姓名:%@-------身份证:%@-------手机号:%@-------公司:%@-------地址:%@-------产品类型:%@",
                             [data valueForKey:@"name"],[data valueForKey:@"ID"],[data valueForKey:@"mobile"],
                             [data valueForKey:@"company"],[data valueForKey:@"address"],[data valueForKey:@"productCategory"]
                             ];
        [self formOperate:message andType:2 andData:data];
    }else if ([data valueForKey:@"inputform"]) {
        //提交表单
        NSDictionary *info = [data valueForKey:@"formTemplate"];
        [self formOperate:@"客服邀请您填写表单～" andType:4 andData:info];
    }
}


-(void)onScreenSnapshotRequest{
    [self snapshot];
}

-(void)OnResourceData:(id)data{
    [self formOperate:@"查看资源文件" andType:1 andData:data];
}

#pragma mark 上传画面截图
-(void)snapshot{
    UIImage *snapshotimage = [self imageWithView:self.localVideoView];
    [self uploadImage:snapshotimage];
}

- (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

-(void)uploadImage:(UIImage *)image{
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    [self.ivcsSdk shareResourceWithType:@"pic" uploadUrl:@"https://ivcs-demo.zealcomm.cn:3094/v1/upload" fileData:imageData fileName:@"test.png" mimeType:@"image/png" toRoles:@"agents" onSuccess:^{
        NSLog(@"...11$success");
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"...11%@!",error);
    }];
}


-(void)formOperate:(NSString *)info andType:(int)opType andData:(NSDictionary *)data{
     UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                       message:info
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  if (opType == 1) {
                                                                      NSString *link = [data valueForKey:@"url"];
                                                                      [self openWebView:link];
                                                                  }else if(opType == 2){
                                                                      //确认个人信息
                                                                     [self sureMyInfo:[NSMutableDictionary dictionaryWithDictionary:data]];
                                                                  }else if(opType == 3){
                                                                      //手写签名
                                                                      HandSignViewController *vc = [[HandSignViewController alloc] init];
                                                                      vc.delegate = self;
                                                                      vc.ivcsSdk = self.ivcsSdk;
                                                                      [self.navigationController pushViewController:vc animated:false];
                                                                  }else if(opType == 4){
                                                                      //填写个人信息
                                                                      FormTableViewController *vc = [[FormTableViewController alloc] init];
                                                                     vc.ivcsSdk = self.ivcsSdk;
                                                                     vc.sessionId = self.sessionId;
                                                                     vc.formTemplateData = data;
                                                                     [self.navigationController pushViewController:vc animated:false];
                                                                  }
                                                                 
                                                              }];
//        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
//                                                             handler:^(UIAlertAction * action) {
//                                                                 //响应事件
//                                                                 NSLog(@"action = %@", action);
//                                                             }];
//        [alert addAction:cancelAction];
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
}

-(void)sureMyInfo:(NSMutableDictionary *)info{
    [self.ivcsSdk sureUserInfoWithSessionId:self.sessionId url:@"https://ivcs-demo.zealcomm.cn/api/forminfo" userInfo:info onSuccess:^{
        NSLog(@"sure info successs");
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"..23%@",error);
    }];
}

-(void)openWebView:(NSString *)link{
    WebLoginViewController *vc = [[WebLoginViewController alloc] init];
    vc.linkUrl = link;
    vc.ivcsSdk = self.ivcsSdk;
    NSLog(@"linkUrl:%@",vc.linkUrl);
    [self.navigationController pushViewController:vc animated:false];
}


@end
